﻿using Admin.NET.Core.Service;
using Admin.NET.Application.Const;
using Admin.NET.Application.Entity;
using Microsoft.AspNetCore.Http;
using System.Web;
using Magicodes.ExporterAndImporter.Excel;
using Magicodes.ExporterAndImporter.Core;
using Furion.DatabaseAccessor;
namespace Admin.NET.Application;
/// <summary>
/// 教师服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class TeacherService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Teacher> _rep;
    private readonly SqlSugarRepository<SysFile> _fileRep;

    private readonly SqlSugarRepository<SysUser> _sysUserRep;
    private readonly SqlSugarRepository<SysUserRole> _sysUserRoleRep;
    private readonly SqlSugarRepository<SysRole> _sysRoleRep;

    public TeacherService(SqlSugarRepository<Teacher> rep, SqlSugarRepository<SysFile> fileRep, SqlSugarRepository<SysUser> sysUserRep, SqlSugarRepository<SysUserRole> sysUserRoleRep, SqlSugarRepository<SysRole> sysRoleRep)
    {
        _rep = rep;
        _fileRep = fileRep;
        _sysUserRep = sysUserRep;
        _sysUserRoleRep = sysUserRoleRep;
        _sysRoleRep = sysRoleRep;
    }

    /// <summary>
    /// 分页查询教师
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<TeacherOutput>> Page(TeacherInput input)
    {
        var query = _rep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.Xuhao.Contains(input.SearchKey.Trim())
                || u.Code.Contains(input.SearchKey.Trim())
                || u.Name.Contains(input.SearchKey.Trim())
                || u.Tel.Contains(input.SearchKey.Trim())
                || u.UserName.Contains(input.SearchKey.Trim())
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.Xuhao), u => u.Xuhao.Contains(input.Xuhao.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Tel), u => u.Tel.Contains(input.Tel.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.UserName), u => u.UserName.Contains(input.UserName.Trim()))
            .Select<TeacherOutput>();
        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加教师
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task<long> Add(AddTeacherInput input)
    {
        var entity = input.Adapt<Teacher>();
        await _rep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除教师
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(DeleteTeacherInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _rep.FakeDeleteAsync(entity);   //假删除
        //await _rep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新教师
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(UpdateTeacherInput input)
    {
        var entity = input.Adapt<Teacher>();
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取教师
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<Teacher> Detail([FromQuery] QueryByIdTeacherInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取教师列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<TeacherOutput>> List([FromQuery] TeacherInput input)
    {
        return await _rep.AsQueryable().Select<TeacherOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取教师导入列表预览
    /// </summary>
    /// <param name="fileId">文件Id</param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "ImportPreview")]
    public async Task<List<TeacherImportDto>> ImportPreview([FromQuery] long fileId)
    {
        var file = _fileRep.GetById(fileId);
        var filePath = App.WebHostEnvironment.WebRootPath;
        filePath = System.IO.Path.Combine(filePath,file.FilePath);
        filePath = System.IO.Path.Combine(filePath, file.Id.ToString());
        filePath += file.Suffix;

        IImporter importer = new ExcelImporter();
        var res = await importer.Import<TeacherImportDto>(filePath);
        var data = new List<TeacherImportDto>();
        foreach (var item in res.Data)
        {
            data.Add(new TeacherImportDto
            {
                Xuhao = item.Xuhao,
                Code = item.Code,
                Name = item.Name,
                Tel = item.Tel,
                UserName = item.UserName,
                Msg = item.Msg,
            });
        }
        return data;
    }

    /// <summary>
    /// 教师导入
    /// </summary>
    /// <param name="teacherListImportDto">用户导入的教师表</param>
    /// <returns></returns>
    [HttpPost]
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "Import")]
    public async Task Import(List<TeacherImportDto> teacherListImportDto)
    {
        foreach (var item in teacherListImportDto)
        {
            var teacher = await _rep.AsQueryable().Where(p => p.UserName == item.UserName).FirstAsync();
            if (teacher == null)
            {
                teacher = new Teacher
                {
                    Xuhao = item.Xuhao,
                    Code = item.Code,
                    Name = item.Name,
                    Tel = item.Tel,
                    UserName = item.UserName,
                    IsAtBook = true,
                    IsAtSchool = true,
                };
                await _rep.InsertAsync(teacher);
            }
            else
            {
                teacher.Xuhao = item.Xuhao;
                teacher.Code = item.Code;
                teacher.Name = item.Name;
                teacher.Tel = item.Tel;
                teacher.IsAtBook = true;
                teacher.IsAtSchool = true;
                await _rep.UpdateAsync(teacher);
            }
        }
    }

    /// <summary>
    /// 初始化学生账号
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "InitTeacherUser")]
    public async Task InitTeacherUser(List<long> input)
    {
        var role = await _sysRoleRep.AsQueryable().Where(p => p.Name == "教师").FirstAsync();
        foreach (long id in input)
        {
            try
            {
                var teacher = await _rep.GetByIdAsync(id);

                var password = teacher.Tel;
                var encryptPassword = CryptogramUtil.Encrypt(password);

                var user = await _sysUserRep.GetByIdAsync(teacher.Id);
                bool isNew = false;
                if (user == null)
                {
                    user = new SysUser { Id = 1300000000101, Account = "superadmin", Password = encryptPassword, NickName = "学生", RealName = "学生", Phone = "18020030720", Birthday = DateTime.Parse("2000-01-01"), Sex = GenderEnum.Male, AccountType = AccountTypeEnum.Member, Remark = "学生", CreateTime = DateTime.Parse("2022-02-10 00:00:00"), TenantId = 1300000000001 };
                    user.Id = teacher.Id;
                    user.Account = teacher.UserName;
                    user.AccountType = AccountTypeEnum.NormalUser;
                    isNew = true;
                }
                user.NickName = teacher.Name;
                user.RealName = teacher.Name;
                user.Password = encryptPassword;
                user.Phone = teacher.Tel;
                if (isNew)
                    await _sysUserRep.InsertAsync(user);
                else
                    await _sysUserRep.UpdateAsync(user);

                var userRole = await _sysUserRoleRep.AsQueryable().Where(p => p.UserId == user.Id && p.RoleId == role.Id).FirstAsync();
                if (userRole == null)
                {
                    await _sysUserRoleRep.InsertAsync(new SysUserRole { UserId = user.Id, RoleId = role.Id });
                }
            }
            catch (Exception ex)
            {
            }

        }
    }
    
}

